using System;
using System.Linq;
using System.Reflection;
using CommandLineMapper.Helpers;
using CommandLineMapper.Interfaces;

namespace CommandLineMapper {
    internal class PropertyHandler : IPropertyHandler {
        private readonly PropertyInfo _propertyInfo;
        private readonly ICommandOption _commandOption;

        public PropertyHandler(PropertyInfo propertyInfo, ICommandOption commandOption) {
            AssertUtils.AssertArgumentNull(propertyInfo, "propertyInfo");
            AssertUtils.AssertArgumentNull(commandOption, "commandOption");
            _propertyInfo = propertyInfo;
            _commandOption = commandOption;
        }

        #region Implementation of IPropertyHandler

        public bool IsKeyMatch(string key) {
            AssertUtils.AssertArgumentNullForString(key, "key");
            return _commandOption.Aliases
                .Any(a => String.Equals(a, key, StringComparison.InvariantCultureIgnoreCase));
        }

        public void SetValue(object instance, string value) {
            AssertUtils.AssertArgumentNull(instance, "instance");
            AssertUtils.AssertArgumentNullForString(value, "value");
            object obj = _commandOption.Converter.ConvertFromInvariantString(value);
            //object obj = _commandOption.Converter.ConvertFromString(value);
            _propertyInfo.SetValue(instance, obj, null);
        }

        #endregion
    }
}